package com.blb.demo2;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CharServer {

    public static final int PORT=8888;
    //CPU每个核执行的线程数
    public static final int THREADS=2;

    public void start(){
        int cpunum = Runtime.getRuntime().availableProcessors();
        //创建自定义的线程池
        ExecutorService executorService = new ThreadPoolExecutor(cpunum * THREADS, cpunum * THREADS, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        System.out.println("启动聊天服务");
        try (ServerSocket serverSocket= new ServerSocket(PORT)){
            while (true){
                //获取客户端连接
                Socket client = serverSocket.accept();
                //获得输入输出流，启动两个线程，分别完成读和写
                executorService.execute(new ReadRunnable(new ObjectInputStream(client.getInputStream())));
                executorService.execute(new WriteRunnable(new ObjectOutputStream(client.getOutputStream())));
            }
        } catch (IOException e) {
           e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        (new CharServer()).start();


    }


}
